package cn.com.ccxcredit.wallet.ui;

import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.web3j.crypto.Credentials;
import org.web3j.crypto.WalletUtils;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.ccxcredit.wallet.R;
import cn.com.ccxcredit.wallet.app.RApplication;
import cn.com.ccxcredit.wallet.config.SystemConfig;
import cn.com.ccxcredit.wallet.observer.SimpleObserve;
import cn.com.ccxcredit.wallet.util.HttpUiTips;
import credit.ccx.com.walletcore.base.BaseApplication;
import credit.ccx.com.walletcore.coin.CoinType;
import credit.ccx.com.walletcore.model.WalletModel;
import credit.ccx.com.walletcore.util.SPUtils;
import credit.ccx.com.walletcore.util.WalletExtUtils;
import huixue.cn.com.library.base.SimpleActivity;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


public class MakeWalletActivity extends SimpleActivity {

    @BindView(R.id.tv_gen_private)
    TextView tvGenPrivate;
    @BindView(R.id.tv_gen_pub)
    TextView tvGenPub;
    @BindView(R.id.tv_gen_address)
    TextView tvGenAddress;
    @BindView(R.id.btn_gen_wallet)
    Button btnGenWallet;
    @BindView(R.id.btn_restore_wallet)
    Button btnRestoreWallet;
    @BindView(R.id.btn_query_balance)
    Button btnQueryBalance;

    private String coin;


    @Override
    public int getLayout() {
        return R.layout.activity_make_wallet;
    }

    @Override
    public void initView() {
        coin = getIntent().getStringExtra("coin");
    }

    @Override
    public void addEvent() {

    }

    @OnClick({R.id.btn_gen_wallet, R.id.btn_restore_wallet,R.id.btn_query_balance})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_gen_wallet:
                initWallet();
                break;
            case R.id.btn_restore_wallet:
                restoreWallet();
                break;
            case R.id.btn_query_balance:
                Intent intent = new Intent(MakeWalletActivity.this,BalanceActivity.class);
                startActivity(intent);
                break;
        }


    }

    private void initWallet() {
        HttpUiTips.showDialog(this,true, "loading...");
        /*Observable.create(new ObservableOnSubscribe<WalletModel>() {
            @Override
            public void subscribe(ObservableEmitter<WalletModel> e) throws Exception {
                if (CoinType.COIN_TYPE_BTC.getName().equals(coin)) {
                    WalletModel walletModel = WalletExtUtils.generateBip39WalletBTC("",
                            RApplication.mnemonic,
                            new File(SystemConfig.getSystemConfig().getRestoreFile()));
                    e.onNext(walletModel);

                } else if (CoinType.COIN_TYPE_ETH.getName().equals(coin)) {
                    WalletModel walletModel = WalletExtUtils.generateBip39WalletETH("",
                            RApplication.mnemonic,
                            new File(SystemConfig.getSystemConfig().getRestoreFile()));
                    e.onNext(walletModel);
                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SimpleObserve<WalletModel>() {
                    @Override
                    public void onNext(WalletModel model) {
                        super.onNext(model);
                        HttpUiTips.dismissDialog(MakeWalletActivity.this);
                        tvGenPrivate.setText("私钥：" + model.getPrivateKey());
                        tvGenPub.setText("公钥：" + model.getPubKey());
                        tvGenAddress.setText("地址：" + model.getAddress());
                    }
                });*/
        Observable.create(subscriber->{
            WalletModel walletModel = null;
            if (CoinType.COIN_TYPE_BTC.getName().equals(coin)) {
                walletModel = WalletExtUtils.generateBip39WalletBTC("",
                        RApplication.mnemonic,
                        new File(SystemConfig.getSystemConfig().getRestoreFile()));
                subscriber.onNext(walletModel);

            }else if (CoinType.COIN_TYPE_ETH.getName().equals(coin)) {
                walletModel = WalletExtUtils.generateBip39WalletETH("",
                        RApplication.mnemonic,
                        new File(SystemConfig.getSystemConfig().getRestoreFile()));

            }
            subscriber.onNext(walletModel);
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(entity ->{
                    HttpUiTips.dismissDialog(MakeWalletActivity.this);
                    tvGenPrivate.setText("私钥：" + ((WalletModel)entity).getPrivateKey());
                    tvGenPub.setText("公钥：" + ((WalletModel)entity).getPubKey());
                    tvGenAddress.setText("地址：" + ((WalletModel)entity).getAddress());
                },onError->{

                });
    }


    private void restoreWallet() {
        Observable.create(new ObservableOnSubscribe<WalletModel>(){
            @Override
            public void subscribe(ObservableEmitter<WalletModel> e) throws Exception {
                String path = (String) SPUtils.get(BaseApplication.application, "P_ETH", "");
                try {
                    Credentials credentials = WalletUtils.loadCredentials("", path);
                    WalletModel walletModel = new WalletModel(credentials.getAddress(), credentials.getEcKeyPair().getPrivateKey().toString(),
                            credentials.getEcKeyPair().getPublicKey().toString(),
                            "");
                    e.onNext(walletModel);
                    Log.d("ChannelIndex","地址："+walletModel.getAddress());

                } catch (Exception ex) {

                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SimpleObserve<WalletModel>() {
                    @Override
                    public void onNext(WalletModel model) {
                        super.onNext(model);
                        tvGenPrivate.setText("私钥：" + model.getPrivateKey());
                        tvGenPub.setText("公钥：" + model.getPubKey());
                        tvGenAddress.setText("地址：" + model.getAddress());
                    }
                });


    }

}
